/**
 * Created by 大发 on 2018/01/22.
 */
// import Cookies from 'js-cookie'
import store from '../store/index'
import authApi from '../api/auth/auth'

let path = require('path')

let util = {
  /**
   * 获取当前登录用户
   * @returns {*}
   */
  user () {
    try {
      return Cookies.getJSON('user')
    } catch (err) {
      console.log('Get User Failed', err)
      return false
    }
  },
  /**
   * 设置登录后回跳地址
   * @param url
   */
  // setAuthRedirect (url = '/home/index') {
  //   Cookies.set('authRedirect', url)
  // },
  /**
   * 获取登录后回跳地址
   * @returns {*|string}
   */
  // getAuthRedirect () {
  //   return Cookies.get('authRedirect') || '/home/index'
  // },
  /**
   * 登录
   */
  // login (user) {
  //   Cookies.set('user', user, 1 / 12)
  //   store.commit('setUser', user)
  // },
  /**
   * 登出
   */
  // logout () {
  //   Cookies.remove('user')
  //   window.location.reload()
  // },
  /**
   * 检查登录用户是否拥有该权限
   * @param permission
   */
  hasPermission (permission) {
    let user = this.user()
    return user.permissions.find(item => {
      return item === permission
    })
  },
  fetchUser (cb) {
    let self = this
    authApi.fetchUser(user => {
      self.login(user)
      cb(user)
    })
  },
  readFileAsBinaryString (file) {
    return new Promise(function (resolve, reject) {
      if (window.FileReader) {
        let reader = new FileReader()
        reader.onloadend = function (e) {
          if (e.type === 'loadend') {
            resolve(reader)
          } else {
            reject(new Error(400))
          }
        }
        reader.readAsArrayBuffer(file)
      }
      else {
        reject(new Error(400))
      }
    })
  },
  readFileAsDataURL (file) {
    return new Promise(function (resolve, reject) {
      let newReader = new FileReader()
      newReader.onload = function (e) {
        // console.log(e.type)
        if (e.type === 'load') {
          resolve(newReader)
        } else {
          reject(new Error(400))
        }
      }
      newReader.readAsDataURL(file)
    })
  },
  usableUploadFileType (uploadExts) {
    uploadExts.forEach((element, extsIndex) => {
      uploadExts[extsIndex] = '.' + uploadExts[extsIndex]
    })
    return uploadExts.join(',')

  },
  parseFileName (filename) {
    let filenameArr = filename.split('.')
    let ext = filenameArr.pop()
    return {filename: filenameArr.join('.'), ext: ext}
  }
}
export default util
